import React, { Component } from 'react';
import Record from './components/Record';
// jQuery 库中 有太多的属性和方法，引入之后很多都不会使用所以需要优化
// import $ from 'jquery';
// import { getJSON } from 'jquery';
// import axios from 'axios';
import * as RecordAPI from './utils/Config';
import RecordForm from './components/RecordForm';
import AmountBox from './components/AmountBox';

export default class App extends Component {
  constructor() {
    super();
    this.state = {
      records: [],
      error: null,
      isLoaded: false
    }
  }

  componentDidMount() {
    // 请求数据
    // $.getJSON('http://5b67a538f793e000145625fa.mockapi.io/api/v2/records')
    // .then(response=>{
    //   this.setState({
    //     records: response
    //   })
    // },
    //   error=>console.log(error)
    // )

    // getJSON('http://5b67a538f793e000145625fa.mockapi.io/api/v2/records')
    //   .then(response => {
    //     this.setState({
    //       records: response,
    //       isLoaded: true
    //     })
    //   },
    //     error => this.setState({
    //       isLoaded: true,
    //       error
    //     })
    //   )

    // axios.get('http://5b67a538f793e000145625fa.mockapi.io/api/v2/records')
    // .then(response => {     
    //   this.setState({
    //     records: response.data,
    //     isLoaded: true
    //   })
    // })
    // .catch(error => {
    //   this.setState({
    //     isLoaded: true,
    //     error
    //   })
    // });

    // axios.get(`${RecordAPI.api}/api/v2/records`)
    //   .then(response => {
    //     this.setState({
    //       records: response.data,
    //       isLoaded: true
    //     })
    //   })
    //   .catch(error => {
    //     this.setState({
    //       isLoaded: true,
    //       error
    //     })
    //   });


    RecordAPI.getRecords().then(response => {
      this.setState({
        records: response.data,
        isLoaded: true
      })
    })
    .catch(error => {
      this.setState({
        isLoaded: true,
        error
      })
    });
  }

  addRecord (msg) {
    this.setState({
      error: null,
      isLoaded: true,
      records: [
        ...this.state.records,
        msg
      ]
    })
  }

  updateRecord (record,msg) {
    const a = {'a':'a'};
    const b = { 'a': 'b' };
    const c = {
      ...a,
      ...b
    }
    
    const recordIndex = this.state.records.indexOf(record);
    console.log(recordIndex);
    
    const newRecord = this.state.records.map((item, index)=>{
      if (index !== recordIndex) {
        return item;
      }
      return {
        ...item,
        ...msg
      }
    });

    this.setState({
      records: newRecord
    })


  }

  deleteRecord (record) {
    const recordIndex = this.state.records.indexOf(record);
    const newRecords = this.state.records.filter((item, index)=>{
      return index !== recordIndex;
    });
    this.setState({
      records: newRecords
    })
  }

  income() {
    let income = this.state.records.filter((record)=>{
      return record.amount > 0;
    })
  }

  income() {
    let incomes = this.state.records.filter((record) => {
      return record.amount > 0;
    })

    return incomes.reduce((prev, curr)=>{
      return prev + Number.parseInt(curr.amount,0);
    },0);
  }

  expenditure() {
    let expend = this.state.records.filter((record) => {
      return record.amount < 0;
    })
    return expend.reduce((prev, curr) => {
      return prev + Number.parseInt(curr.amount, 0);
    }, 0);
  }

  totalAmount() {
    return this.income() + this.expenditure();
  }

  render() {
    const { error, isLoaded, records } = this.state;

    let recordComponent;

    if (error) {
      // return <div>Error:{error.responseText}</div>
      // return <div>Error:{error.message}</div>
      recordComponent = <div>Error:{error.message}</div>;
    } else if (!isLoaded) {
      // return <div>Loading......</div>
      recordComponent = <div> Loading...... </div>;
    } else {
      recordComponent = (
        <div>
          <table className="table table-bordered">
            <thead>
              <tr>
                <th>日期</th>
                <th>内容</th>
                <th>总计</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {/* {this.state.records.map((item) =><Record key={item.id} record={item} />)} */}
              {/* {records.map((item) => <Record key={item.id} {...item} handleUpdateRecord={this.updateRecord.bind(this)}/>)} */}
              {/* TODO:为了能整条取得 记录，需要使用 自定义行内属性，通过props.属性 获取该条数据 */}
              {records.map((item) => <Record key={item.id} record={item} handleUpdateRecord={this.updateRecord.bind(this)} handleDeleteRecord={this.deleteRecord.bind(this)}/>)}
            </tbody>
          </table>
        </div>
      );
    }

    return (
      <div>
        <h2>小型财务管理系统</h2>
        <div className="row ml-3 mb-3">
          <AmountBox text="收入" type="success" amount={this.income()}/>
          <AmountBox text="支出" type="danger" amount={this.expenditure()} />
          <AmountBox text="合计" type="info" amount={this.totalAmount()} />
        </div>
        <RecordForm handleNewRecord={this.addRecord.bind(this)}/>
        {recordComponent}
      </div>
    )

  }
}

